import { BASE_URL } from "../../utils/config";

interface Course {
  id: number;
  courseName: string;
  icon: string;
  color: string;
  checkType: number;
  lat: number;
  lon: number;
  distance: number;
}

Page({
  data: {
    latitude: 23.099994,
    longitude: 113.324520,
    markers: [] as any[],
    scale: 14,
    isClockIn: false,
    course: {} as Course
  },

  // 获取当前位置
  async getCurrentLocation() {
    try {
      const res = await this.getLocation();
      console.log('当前位置:', res);
      this.setData({
        latitude: res.latitude,
        longitude: res.longitude,
        markers: [{
          id: 1,
          latitude: res.latitude,
          longitude: res.longitude,
          callout: {
            content: '当前位置',
            color: '#333333',
            fontSize: 14,
            borderRadius: 4,
            padding: 8,
            display: 'ALWAYS',
            bgColor: '#ffffff'
          }
        }]
      });
    } catch (error) {
      console.error('获取位置失败:', error);
      wx.showToast({
        title: '获取位置失败',
        icon: 'error'
      });
    }
  },

  // 获取位置Promise封装
  getLocation(): Promise<WechatMiniprogram.GetLocationSuccessCallbackResult> {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: resolve,
        fail: reject
      });
    });
  },
  fetchCourse(courseId: number) {
    const token = wx.getStorageSync('token');
    // 从后端获取课程数据
    wx.request({
      url: `${BASE_URL}/course/selectOne`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        id: courseId
      },
      success: (res: any) => {
        const { code, data } = res.data;
        if (code === 200) {
          this.setData({
            course: data
          });
        } else {
          wx.showToast({
            title: res.data.msg || '查询失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '查询失败',
          icon: 'error'
        });
      }
    });
  },
  // 使用Haversine公式计算两点之间的距离（单位：米）
  calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
    const R = 6371000; // 地球半径（米）
    const rad = Math.PI / 180;
    const dLat = (lat2 - lat1) * rad;
    const dLon = (lon2 - lon1) * rad;
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(lat1 * rad) * Math.cos(lat2 * rad) *
              Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
  },

  locationCheck() {
    // 计算一下距离
    const distance = this.calculateDistance(this.data.latitude, this.data.longitude, this.data.course.lat, this.data.course.lon);
    console.log(distance);
    // 如果距离小于distance米，打卡成功
    if (distance < this.data.course.distance) {
      // 直接打卡
      const token = wx.getStorageSync('token');
      wx.request({
        url: `${BASE_URL}/check/locationSave`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        },
        data: {
          courseId: this.data.course.id,
          lat: this.data.latitude,
          lon: this.data.longitude,
          distance: distance
        },
        success: (res: any) => {
          const { code } = res.data;
          if (code === 200) {
            this.setData({
              isClockIn: true
            }, () => {
              wx.showToast({
                title: '打卡成功',
                icon: 'success'
              });

              setTimeout(() => {
                // 返回上一页
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }, 1000);
              
            });
          } else {
            wx.showToast({
              title: res.data.msg || '打卡失败',
              icon: 'error'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '打卡失败',
            icon: 'error'
          });
        }
      });
    } else {
      // 提示距离过远
      wx.showToast({
        title: '距离过远，距离为' + distance + '米',
        icon: 'error'
      })
    }
  },
  onLoad(options: any) {
    // 页面加载时获取位置
    this.getCurrentLocation();
    // 获取课程数据
    this.fetchCourse(options.courseId);
  }
});